from fastapi import FastAPI
from fastapi.responses import JSONResponse
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from tortoise.contrib.fastapi import register_tortoise
from apps.settings.db import TORTOISE_ORM
from apps.test.api.test import myTest

from apps.api import users, rooms, websockets, gameplay

app = FastAPI(
    middleware=[
        Middleware(
            SessionMiddleware,
            # 设置session的解密key
            secret_key="evan&liwei",
            # 设置前端接收到的session的key值(Cookie都是 key:value 形式)
            session_cookie="usersession",
            # session过期时间
            max_age=3600,
            # 生产环境中使用，指定域名
            domain=".yofunn.top", # 注意'.'必须要带
            https_only=True
        )
    ]
)

# 跨域中间件
app.add_middleware(
    CORSMiddleware,  # 添加CORS跨域中间件
    allow_origins=["http://localhost:8080"],  # 允许所有来源访问，生产环境建议改为具体域名
    allow_credentials=True,  # 允许跨域请求携带认证信息(cookies等)
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有请求头
)

# 注册tortoise-orm
register_tortoise(		# 这个方法只会在FastAPI启动时触发,app对象会监听服务的启动和终止
    app,
    config=TORTOISE_ORM,
    generate_schemas=True,
)

@app.get("/")
async def root():
    return JSONResponse(content={"message": "你好,世界~"})

app.title = "FastAPI德州扑克牌游戏API"
app.version = "v1.0.0"
# 导入路由
app.include_router(myTest, prefix='/test', tags=['测试接口,仅供测试使用'])
app.include_router(users, prefix='/api')
app.include_router(rooms, prefix='/api')
app.include_router(gameplay, prefix='/api')
app.include_router(websockets, prefix='/api')


if __name__ == '__main__':
    import uvicorn
    print('API接口文档地址：http://127.0.0.1:8000/docs')
    uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True, log_level='debug')